package com.dldata.devtools30.utils;

import java.io.InputStream;
import java.nio.ByteBuffer;
import java.security.MessageDigest;

/**

 */
public class MD5Util {

    public final static String MD5Encoder(String s) {
        try {
            byte[] btInput = s.getBytes("utf-8");
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < md.length; i++) {
                int val = ((int) md[i]) & 0xff;
                if (val < 16){
                    sb.append("0");
                }
                sb.append(Integer.toHexString(val));
            }
            return sb.toString();
        } catch (Exception e) {
            return null;
        }
    }

    public final static String MD5Encoder(byte[] btInput ) {
        try {
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            if(btInput.length<1024*1024*6){
                mdInst.update(btInput);
            }else {
                ByteBuffer byteBuffer=ByteBuffer.wrap(btInput);
                mdInst.update(byteBuffer);
            }
            byte[] md = mdInst.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < md.length; i++) {
                int val = ((int) md[i]) & 0xff;
                if (val < 16){
                    sb.append("0");
                }
                sb.append(Integer.toHexString(val));
            }
            return sb.toString();
        } catch (Exception e) {
            return null;
        }
    }


    public final static String MD5Encoder(InputStream inputStream) {
        try {
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            byte[] btInput=new byte[1024*1024*3];
            int length=-1;
            while ((length=inputStream.read(btInput))!=-1){
                mdInst.update(btInput,0,length);
            }
            byte[] md = mdInst.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < md.length; i++) {
                int val = ((int) md[i]) & 0xff;
                if (val < 16){
                    sb.append("0");
                }
                sb.append(Integer.toHexString(val));
            }
            return sb.toString();
        } catch (Exception e) {
            return null;
        }
    }


}
